package com.csust.travel.controller;

import cn.hutool.core.util.RandomUtil;
import com.csust.travel.entity.ResBean;
import com.csust.travel.service.AsyncEmailService;
import com.csust.travel.service.CodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/email")
public class EmailController {

    @Autowired
    private CodeService codeService;

    @Autowired
    private AsyncEmailService asyncEmailService;

    /**
     * 获取验证码
     * @param email 收件人
     * @return 验证码信息
     */
    @GetMapping("/code")
    public ResBean getCode(@RequestParam("email") String email) {
        System.out.println(email + "  1111");

        // 生成并缓存验证码
        codeService.generateAndCacheCode(email);

        // 从缓存中获取验证码（不移除）
        String code = codeService.getAndKeepCode(email);

        System.out.println(code + " 8080");

        // 异步发送邮件
        asyncEmailService.sendEmail(email, code);

        return new ResBean(true, "发送成功");
    }
}
